<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="采集商品ID：" prop="collectProductId">
        <el-select v-model="queryParams.collectProductId" filterable>
          <el-option v-for="(item,index) in productIdList" :key="index" :label="item"
                     :value="item"></el-option>
        </el-select>
        <!--        <el-input v-model="queryParams.collectProductId" placeholder="请输入采集商品ID" clearable-->
        <!--                  @keyup.enter.native="handleQuery"/>-->
      </el-form-item>
      <el-form-item v-if="isSupervisor" label="负责人：" prop="headUserName">
        <el-select v-model="queryParams.headUserId" placeholder="请选择负责人" filterable>
          <el-option v-for="item in peopleList" :key="item.value" :label="item.label"
                     :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="优化状态：" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择优化状态">
          <el-option v-for="item in dict.type.erp_optimize_plan_status" :key="item.value" :label="item.label"
                     :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否含有品牌" prop="isBrand">
        <el-select v-model="queryParams.isBrand" placeholder="请选择是否含有品牌" clearable>
          <el-option v-for="dict in dict.type.atlas_has_brand" :key="dict.value" :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="isSupervisor">
        <el-button type="danger" plain size="mini" @click="withdrawDistribution()">一键撤回</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getImageList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="imgDetailList" border stripe @selection-change="handleSelectionChange"
              :key="isUpdateTable">
      <el-table-column type="selection" width="40" align="center"></el-table-column>
      <el-table-column label="原图" min-width="100" align="center">
        <template slot-scope="scope">
          <div>
            <image-preview
              :src="scope.row.optimizePic.indexOf('?') != -1?scope.row.optimizePic.substring(0, scope.row.optimizePic.indexOf('?')):scope.row.optimizePic"
              width="70px" height="70px"></image-preview>
            <!--                <image-upload v-model="scope.row.optimizePic" :changeSize="true" :isShowTip="false" :limit="1"/>-->
          </div>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="200" align="">
        <template slot-scope="scope">
          <div v-for="(item,index) in scope.row.remarks.split('##')">
            {{ item }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="优化图" min-width="250" align="center">
        <template slot-scope="scope">
          <!--              <image-upload v-model="scope.row.pics" :changeSize="true" :isShowTip="false" :limit="1"/>-->
          <div v-if="scope.row.status == 3">
            <image-preview :src="scope.row.pics" width="150px" height="150px"></image-preview>
          </div>
          <div v-else>
            <image-upload isLimitsize :atlasType="scope.row.type" v-model="scope.row.pics" :changeSize="false"
                          :isShowTip="false" :limit="1" width="150px" height="150px"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" min-width="120" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.erp_optimize_plan_status" :value="scope.row.status"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="isSupervisor" label="标签" min-width="200">
        <template slot-scope="scope">
          <div v-if="scope.row.tagIds">
            <el-tag v-for="(tag,index) in scope.row.tagList" :key="index" style="margin: 5px">
              {{ tag.tagName }}
            </el-tag>
          </div>
          <div v-else>
            <el-select ref="selectHeadEmpId" v-model="scope.row.selectValue" multiple filterable
                       placeholder="选择图片标签">
              <el-option v-for="item in tagList" :key="item.id" :label="item.tagName" :value="item.id"></el-option>
            </el-select>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="150" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.status != 3">
            <div v-if="isSupervisor && scope.row.status != 0 && scope.row.status != 2">
              <el-button size="mini" type="text" @click="changeStatus(scope.row,'1')">
                确定
              </el-button>
              <el-button size="mini" type="text" @click="changeStatus(scope.row,'2')">
                重做
              </el-button>
            </div>
            <div v-if="!isSupervisor && scope.row.status != 1">
              <el-button size="mini" type="text" @click="changeStatus(scope.row,'0')">
                提交
              </el-button>
            </div>
          </div>
          <el-button v-if="isSupervisor" size="mini" type="text" @click="withdrawDistribution(scope.row)">
            撤回
          </el-button>
          <el-button size="mini" type="text" @click="openDetail(scope.row)">
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    <el-tabs v-model="tabsValue" type="border-card" @tab-click="tabsClick">-->
    <!--      <el-tab-pane v-for="(item,index) in tabsList" :key="index" :label="item.label" :name="item.name">-->
    <!--        -->
    <!--      </el-tab-pane>-->
    <!--    </el-tabs>-->
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getImageList"/>
    <!--  重置原因  -->
    <el-dialog
      title="重做原因"
      :visible.sync="isOpenRemarkModal"
      width="500px">
      <el-form :model="resetInfo" :rules="resetRules" ref="resetInfo" size="small" label-width="120px">
        <el-form-item label="重做原因：" prop="remarks">
          <el-input @input="inputRemark" type="textarea" v-model="resetInfo.remarks" placeholder="请输入重做原因"
                    clearable/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isOpenRemarkModal = false">取 消</el-button>
        <el-button type="primary" @click="restTask">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryOptimizeHeadUser,
  taskList,
  supervisorReviewPass,
  supervisorReviewRedo,
  headUserPostOptimize,
  queryThisUserRole, getTagList, userCollectProductList
} from '@/api/picture/picture'
import Dict from "@/views/system/dict/index.vue";
import {cancelPlanToHeadOptimize} from "@/api/picture/optimizeTask";

export default {
  components: {Dict},
  dicts: ["erp_optimize_plan_status", 'atlas_has_brand'],
  data() {
    return {
      resetInfo: {},
      tagList: [],//标签列表
      resetRules: {
        remarks: [{
          required: true,
          message: '任务备注不能为空',
          trigger: 'blur'
        }],
      },
      isSupervisor: false,//是不是主管
      isDisSelect: true,//是否禁用下拉框
      dynamicTags: [],
      selectValue: "",
      isUpdateTable: false,
      loading: false, // 遮罩层
      chooseProductId: [], // 选中数组
      chooseIds: [],//选中的id数组
      single: true, // 非单个禁用
      multiple: true, // 非多个禁用
      showSearch: true, // 显示搜索条件
      total: 0, // 总条数
      imgDetailList: [], // 卖家订单表格数据
      isOpenRemarkModal: false,//重置填写备注弹窗
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: "",//优化状态
        headUserName: "",//负责人姓名
        collectProductId: "",//采集商品id
        headUserId: null,//负责人id
        type: "",// 图集类型
      }, // 查询参数
      tabsValue: 0,
      isShowEditPicture: true,
      tabsList: [
        {
          name: '0',
          label: '轮播图'
        }, {
          name: '1',
          label: '详情图'
        }, {
          name: '2',
          label: '场景图'
        }, {
          name: '3',
          label: '白底图'
        }
      ],
      peopleList: [],
      collectProductId: "",
      userInfo: '',
      taskId: "",//任务的id
      productIdList: [],// 采集商品的id
    }
  },
  computed: {
    getEchoTag(e) {
      console.log('e', e)
      return 123
    }
  },
  created() {
    this.userInfo = this.$store.state.user.urserInfo
    this.getUserRouter()
    this.getPeopleList()
    // console.log('dict.type.erp_optimize_plan_status', this.dict.type.erp_optimize_plan_status)
  },
  methods: {
    // 查看详情
    openDetail(row) {
      // this.$router.push({
      //   path: "./detail",
      //   query: row
      // })
      const params = {v1: row.collectProductId, v2: '1', isTask: true};
      this.$tab.openPage("产品详情", '/picture/detail', params)
    },
    // 获取采集商品iD列表
    getProductIdList() {
      let data = {
        userId: this.isSupervisor ? '' : this.userInfo.userId
      }
      userCollectProductList(data).then(res => {
        this.productIdList = res
      })
    },
    // 撤回分配任务
    withdrawDistribution(row) {
      console.log('this.chooseIds', this.chooseIds, row)
      if (!row && this.chooseIds && this.chooseIds.length < 1) {
        this.$message.error('请至少选择一项！')
        return
      }
      this.$confirm("是否确定撤回优化任务", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        let data = {
          ids: row ? row.id : this.chooseIds.toString()
        }
        cancelPlanToHeadOptimize(data).then(res => {
          this.$message.success(res.msg)
          this.getImageList()
        })
      })
    },
    // 获取标签列表
    getTagList() {
      getTagList(this.queryParams).then(response => {
        this.tagList = response.data
        this.getImageList()
      })
    },
    // 查询用户权限
    getUserRouter() {
      let data = {
        userId: this.userInfo.userId
      }
      queryThisUserRole(data).then(res => {
        console.log('ressss', res)
        if (res.msg.indexOf('admin') != -1) {
          this.isSupervisor = true
        }

        if (res.msg.indexOf('art-staff') != -1) {
          this.isSupervisor = false
        } else {
          this.isSupervisor = true
        }
        this.getTagList()
        this.getProductIdList()
      })
    },
    // 获取美工人员列表
    getPeopleList() {
      queryOptimizeHeadUser().then(res => {
        this.peopleList = []
        let list = res.data.sysUserList
        list.map(item => {
          // console.log('888', item)
          this.peopleList.push({
            label: item.nickName,
            value: item.userId
          })
        })
      })
    },
    //  提交优化任务
    changeStatus(row, type) {
      var that = this;
      if (type == '1') {
        console.log('row.selectValue', row, row.selectValue)
        if (((row.selectValue && row.selectValue.length < 1) || !row.selectValue) && !row.tagIds) {
          this.$message.error('请先选择标签！')
          return
        }

        if (!row.pics) {
          this.$message.error('优化图片不能为空！')
          return
        }
      }
      if (type == 0) {
        if (!row.pics) {
          this.$message.error('请上传优化图，优化图片不能为空')
          return
        }
        let imgList = row.pics.split(";")
        console.log('imgList', imgList)
        if (imgList && imgList.length > 1) {
          this.$message.error("优化图最多上传一张！")
          return
        }
      }
      let mssage = type == 0 ? "是否确定提交所编辑的图片？" : type == 1 ? "是否确定使用此优化图片？" : "是否确定重做该商品图片？"
      this.$confirm(mssage, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        this.taskId = row.id
        if (type == '0') {
          that.submitTask(row)
        } else if (type == '1') {
          that.confirmTask(row)
        } else {
          this.resetInfo.remarks = ""
          that.isOpenRemarkModal = true
        }
      })
    },
    inputRemark(e) {
      this.$forceUpdate()
    },
    // 确定任务
    confirmTask(row) {
      console.log('row', row)
      let data = {
        id: this.taskId,
        tagIds: row.selectValue ? row.selectValue.toString() : row.tagIds,
        pic: row.pics
      }
      // console.log('data', data)
      // return
      supervisorReviewPass(data).then(res => {
        console.log(res)
        this.$message({
          type: 'success',
          message: res.msg
        })
        // this.isShowEditPicture = false
        this.getImageList() // 修改完状态后再次获取订单列表
      })
    },
    // 重置任务
    restTask() {
      let data = {
        remarks: this.resetInfo.remarks,
        id: this.taskId,
      }
      supervisorReviewRedo(data).then(res => {
        console.log(res)
        this.$message({
          type: 'success',
          message: res.msg
        })
        this.isOpenRemarkModal = false
        this.getImageList() // 修改完状态后再次获取订单列表
      })
    },
    // 提交任务
    submitTask(row) {
      let data = {
        id: this.taskId,
        pics: row.pics
      }
      headUserPostOptimize(data).then(res => {
        console.log(res)
        this.$message({
          type: 'success',
          message: res.msg
        })
        // this.isShowEditPicture = false
        this.getImageList() // 修改完状态后再次获取订单列表
      })
    },
    // 切换选项卡
    tabsClick(tab, event) {
      console.log(tab.name, event)
      this.selectValue = "" //把下拉框的值置为空
      this.isDisSelect = true
      this.getImageList()
    },
    // 获取图片任务列表
    getImageList() {
      this.loading = true
      if (!this.isSupervisor) {
        this.queryParams.headUserId = this.userInfo.userId
      }
      // this.queryParams.headUserName = null
      // this.queryParams.type = this.tabsValue
      // console.log('this.queryParams', this.queryParams)
      taskList(this.queryParams).then(response => {
        let list = response.rows
        for (let i = 0; i < list.length; i++) {
          if (list[i].tagIds) {
            let tagIds = list[i].tagIds.split(',')
            list[i]['tagList'] = this.tagList.filter(item => tagIds.indexOf(item.id) > -1)
          } else {
            list[i]['tagList'] = this.tagList
          }
        }
        this.imgDetailList = list
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getImageList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.chooseProductId = selection.map(item => item.imgId)
      this.chooseIds = selection.map(item => item.id)
      if (this.chooseProductId && this.chooseProductId.length > 0) {
        this.isDisSelect = false
      } else {
        this.isDisSelect = true
        this.selectValue = ""
      }
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
  }
}
</script>
<style>
.demo-table-expand label {
  width: 100px;
  color: #99a9bf;
  padding: 0;
}
</style>
